package com.dgshanger.sanhxiaofeisc.ui.nearby

import android.content.Intent
import android.support.v4.content.ContextCompat
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import com.amap.api.maps2d.AMapUtils
import com.amap.api.maps2d.model.LatLng
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.dgshanger.sanhxiaofeisc.MainActivity
import com.dgshanger.sanhxiaofeisc.R
import com.dgshanger.sanhxiaofeisc.adapter.NearbyAdapter
import com.dgshanger.sanhxiaofeisc.adapter.NearbyHotAdapter
import com.dgshanger.sanhxiaofeisc.common.Constants
import com.dgshanger.sanhxiaofeisc.entity.HomeEntity
import com.dgshanger.sanhxiaofeisc.entity.NearbyItemEntity
import com.dgshanger.sanhxiaofeisc.mvp.contract.NearbyContract
import com.dgshanger.sanhxiaofeisc.mvp.presenter.NearbyPresenter
import com.dgshanger.sanhxiaofeisc.ui.home.activity.ShopDetailsActivity
import com.dgshanger.sanhxiaofeisc.ui.home.utils.ImageLoader
import com.xx.baseuilibrary.adapter.BaseRecycleAdapter
import com.xx.baseuilibrary.adapter.BaseViewHolder
import com.xx.baseuilibrary.mvp.lcec.BaseMvpLcecFragment
import kotlinx.android.synthetic.main.fragment_nearby.*
import kotlinx.android.synthetic.main.item_nearby_list.view.*
import kotlinx.android.synthetic.main.view_nearby_head.view.*


/**
 * NearbyFragment
 * 沉迷学习不能自拔
 * Describe：
 * Created by 雷小星🍀 on 2018/4/10 18:08.
 */
class NearbyFragment : BaseMvpLcecFragment<SwipeRefreshLayout, List<NearbyItemEntity>, NearbyContract.Model, NearbyContract.View, NearbyPresenter>(), NearbyContract.View, View.OnClickListener {

    override fun onDataFailure(err: String?) {
        mAdapter.loadMoreFail()
    }

    override fun setData(data: List<NearbyItemEntity>?) {
        Log.e("Tag", "setData")
        showContent()
        currentPage++
        contentView.isRefreshing = false
        mAdapter.openLoadAnimation(BaseQuickAdapter.SCALEIN)
        mAdapter.setNewData(data)
        Constants.putNearbyData(data)
    }


    override fun loadData(refresh: Boolean) {
        Log.e("Tag", "loadData")
        if (Constants.isLogin()) {
            ImageLoader.loadAvatar(mContext, mHeaderView.ib_avatar, Constants.getUserEntity()?.avatar)
        } else {
            mHeaderView.ib_avatar.setImageResource(R.color.colorDivler)
        }
        //presenter.loadCategory()
        presenter.loadMerchant(refresh, mLocation[2], mSort_distance, mLocation[1],
                mLocation[0], currentPage.toString(), mSort_new, mSort_comment)
    }

    override fun upDateCategoryList(list: MutableList<HomeEntity.CategoryListBean>?) {

    }

    override fun upDateAddMerchantList(list: MutableList<NearbyItemEntity>?) {
        currentPage++
        if (list != null && !list.isEmpty()) {
            mAdapter.loadMoreComplete()
            mAdapter.addData(list)
        } else {
            mAdapter.loadMoreEnd()
        }
    }

    override fun createPresenter(): NearbyPresenter = NearbyPresenter()

    override fun getFragmentLayoutId(): Int = R.layout.fragment_nearby

    private lateinit var mNearbyHotAdapter: NearbyHotAdapter

    private lateinit var mAdapter: NearbyAdapter
    private lateinit var mLocation: Array<String>
    private var currentPage: Int = 1

    override fun initView(view: View?) {
        super.initView(view)
        contentView.setColorSchemeResources(R.color.colorAccent)
        //热门商家
        recyclerViewMerchant.layoutManager = LinearLayoutManager(mContext)
        mAdapter = NearbyAdapter(R.layout.item_nearby_list, ArrayList())
        mAdapter.addHeaderView(getHeaderView())
        recyclerViewMerchant.adapter = mAdapter
        mAdapter.setOnLoadMoreListener {
                loadData(false)
        }
        contentView.setColorSchemeColors(ContextCompat.getColor(mContext, R.color.colorAccent))
    }

    private lateinit var mHeaderView: View
    private fun getHeaderView(): View? {
        mHeaderView = View.inflate(mContext, R.layout.view_nearby_head, null)
        mHeaderView.ll_distance.setOnClickListener(this)
        mHeaderView.ll_comment.setOnClickListener(this)
        mHeaderView.ll_new.setOnClickListener(this)
        //热门分类
        mHeaderView.recyclerViewHot.layoutManager = LinearLayoutManager(mContext)
        mNearbyHotAdapter = NearbyHotAdapter(R.layout.item_person_center, Constants.getHomeData().category_list)
        //mNearbyHotAdapter = NearbyHotAdapter(R.layout.item_person_center, arrayListOf())
        mHeaderView.recyclerViewHot.adapter = mNearbyHotAdapter
        return mHeaderView
    }

    override fun initEvent(view: View?) {
        mHeaderView.ib_avatar.setOnClickListener {
            //个人中心
            val intent = Intent(mContext, MainActivity::class.java)
            intent.putExtra(Constants.KEY_INTENT_MAIN, MainActivity.INDEX_PERSON)
            startActivity(intent)
        }
        //收藏的商家
        mHeaderView.tv_collectible.setOnClickListener {
            startActivity(CollectibleListActivity::class.java)
        }

        //查看全部分类
        mHeaderView.tv_check_all.setOnClickListener {
            startActivity(CategoryListActivity::class.java)
        }

        //点击分类
        mHeaderView.recyclerViewHot.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                val intent = Intent(mContext, CategoryActivity::class.java)
                intent.putExtra("category_id", mNearbyHotAdapter.data[position].category_id)
                intent.putExtra("category_name", mNearbyHotAdapter.data[position].category_name)
                startActivity(intent)
            }
        })

        //刷新
        contentView.setOnRefreshListener {
            if (!presenter.isLoading!!) {
                currentPage = 1
                loadData(true)
            }
        }
        //商家
        recyclerViewMerchant.addOnItemTouchListener(object : OnItemClickListener() {
            override fun onSimpleItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
                val intent = Intent(mContext, ShopDetailsActivity::class.java)
                intent.putExtra("shop_id", mAdapter.data[position].shop_id)
                intent.putExtra("comment_score", mAdapter.data[position].comment_score)
                startActivity(intent)
            }

        })
    }

    override fun initData() {
        mLocation = Constants.getLocation()
        if (Constants.isFirstNearby()) {
            loadData(true)
        } else {
            showContent()
            mAdapter.setNewData(Constants.getNearbyData())
            currentPage = 2
//            loadData(true)
        }
        Constants.setIsFirstNearby(false)
    }

    override fun onClick(view: View?) {
        when (view!!.id) {
            R.id.ll_distance -> {//距离
                changeUI(0)
            }
            R.id.ll_comment -> {//评价
                changeUI(1)
            }
            R.id.ll_new -> {//最新入驻
                changeUI(2)
            }
        }
    }

    private var isAsc: Boolean = true //是否升序
    private var typeFlag: Int = -1 // 表示是否点击同一个
    private var mSort_distance: String? = null
    private var mSort_new: String? = null
    private var mSort_comment: String? = null
    private fun changeUI(type: Int) {
        if (typeFlag != type) {
            isAsc = true
            typeFlag = type
        }
        setDelUI()
        when (type) {
            0 -> {//距离
                if (isAsc) {//升序
                    mHeaderView.iv_distance_up.setImageResource(R.drawable.xiaoshang_)
                    mSort_distance = "asc"
                    mSort_new = null
                    mSort_comment = null
                } else {
                    mHeaderView.iv_distance_dw.setImageResource(R.drawable.xiaoxia_)
                    mSort_distance = "desc"
                    mSort_new = null
                    mSort_comment = null
                }
                isAsc = !isAsc
            }
            1 -> {//评价
                if (isAsc) {
                    mHeaderView.iv_comment_up.setImageResource(R.drawable.xiaoshang_)
                    mSort_distance = null
                    mSort_new = null
                    mSort_comment = "asc"
                } else {
                    mHeaderView.iv_comment_dw.setImageResource(R.drawable.xiaoxia_)
                    mSort_distance = null
                    mSort_new = null
                    mSort_comment = "desc"
                }
                isAsc = !isAsc
            }
            2 -> {//最新入驻
                if (isAsc) {
                    mHeaderView.iv_new_up.setImageResource(R.drawable.xiaoshang_)
                    mSort_distance = null
                    mSort_new = "asc"
                    mSort_comment = null
                } else {
                    mHeaderView.iv_new_dw.setImageResource(R.drawable.xiaoxia_)
                    mSort_distance = null
                    mSort_new = "desc"
                    mSort_comment = null

                }
                isAsc = !isAsc
            }
        }
        currentPage = 1
        loadData(true)
        showLoadingDialog()
    }

    private fun setDelUI() {
        mHeaderView.iv_distance_up.setImageResource(R.drawable.xiaosan_)
        mHeaderView.iv_distance_dw.setImageResource(R.drawable.huishan_)
        mHeaderView.iv_comment_up.setImageResource(R.drawable.xiaosan_)
        mHeaderView.iv_comment_dw.setImageResource(R.drawable.huishan_)
        mHeaderView.iv_new_up.setImageResource(R.drawable.xiaosan_)
        mHeaderView.iv_new_dw.setImageResource(R.drawable.huishan_)
    }

    private class Adapter : BaseRecycleAdapter<NearbyItemEntity, ViewHolder>() {

        override fun createViewHolder(view: View?, viewType: Int): ViewHolder = ViewHolder(view!!)

        override fun getItemLayout(viewType: Int): Int = R.layout.item_nearby_list
    }


    private class ViewHolder(view: View) : BaseViewHolder<NearbyItemEntity>(view) {

        override fun bindView(position: Int, entity: NearbyItemEntity?) {
            ImageLoader.loadToUrl(itemView.context, itemView.iv_nearby, Constants.getBaseUrl() + entity?.menu_img)
            itemView.tv_nearby_name.text = entity!!.shop_name
            itemView.tv_nearby_grade.text = itemView.context.getString(R.string.tv_grade) + entity.comment_score
            itemView.tv_nearby_category.text = entity.category_name
            itemView.tv_nearby_introduce.text = entity.introduce
            val location = Constants.getLocation()
            val myLatLng = LatLng(location[0].toDouble(), location[1].toDouble())
            val shopLatLng = LatLng(entity.latitude.toDouble(), entity.longitude.toDouble())
            val distanceMeters = AMapUtils.calculateLineDistance(myLatLng, shopLatLng).toInt()
            itemView.tv_nearby_distance.text = distanceMeters.toString() + "m"
        }

    }
}